#include "persistence.h"

QTextStream out(stdout,QIODevice::ReadWrite);

Persistence::Persistence()
{

}

int Persistence::SetTimer(const int time)
{
    if(time <= 0 )return INVALID_TIME;
    QTimer * timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(SaveHashToFile()));
    timer->start(time);
    return 0;
}


int Persistence::SaveHashToFile(const QHash<QString,QString> *Hash,const QString DBDir,const QString DBName)
{
//  out<<GetAppPath()<<endl;
    QFile File(GetAppPath() + DBName);
    File.open(QIODevice::WriteOnly| QIODevice::Text);
    QHash<QString,QString>::const_iterator it = Hash->begin();
    while(it != Hash->end())
    {
        QString Value = it.key() + DBDir + it.value();
        int len = File.write(Value.toLocal8Bit(),Value.size());
        if(len == -1)return WRITE_DATA_FAILED;
    }
    return 0;
}

QString Persistence::GetAppPath()
{
    return QDir::currentPath();
}

int Persistence::UsageTheDBFile(const QString *DBDir,const QString *DBName)
{
    if(DBName->isEmpty())return INVAILD_DBNAME;
    QFile file(GetAppPath() + *DBDir + *DBName);
    if(file.exists()) {ReadDBFile(DBDir,DBName);return 1;}
    file.open(QIODevice::ReadWrite | QIODevice::Text);
    return 0;
}

void Persistence::ReadDBFile(const QString *DBDir,const QString *DBName)
{

}
